<?php

declare(strict_types=1);

namespace hangpu8\hpcms\controller;

use hangpu8\hpcms\Utils\Json;
use thans\jwt\facade\JWTAuth;

class Publics extends Base
{
    // 欢迎界面方法
    public function welcome()
    {
        return Json::successful([],'');
    }

    // 获取用户登录信息
    public function user()
    {
        try {
            $adminService = new \hangpu8\hpcms\service\Login;
            $adminInfo = (array)$adminService->getLoginInfo();
            return Json::successful($adminInfo,'获取数据成功');
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage(),$e->getCode());
        }
    }

    // 获取权限菜单及路由
    public function getMenu()
    {
        $payload = JWTAuth::auth();
        $user_id = (string)$payload['id']->getValue();
        try {
            // 获取权限菜单
            $menuObserver = new \hangpu8\hpcms\service\MenuObserver;
            $rules = $menuObserver->getMenus($user_id);
            
            // 获取菜单
            $menuService = new \hangpu8\hpcms\service\Menu;
            $menus = $menuService->getMenus($rules);

            // // 获取路由
            $routerService = new \hangpu8\hpcms\service\Router;
            $router = $routerService->getVueRouter($rules);
            $data = [
                'router'        => $router,
                'menus'         => $menus
            ];
            return Json::successful($data,'获取权限菜单成功');
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 缓存菜单
     *
     * @return void
     */
    public function cacheMenu()
    {
        try {
            $routerCls = new \hangpu8\hpcms\Utils\Router;
            $routes = $routerCls->getRouterAll(true);
            if ($routes)
            {
                return Json::successful([],'缓存权限菜单成功');
            }else{
                return Json::fail('缓存权限菜单失败');
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }
}
